﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using Castle.MonoRail.Framework;
using Rodunu.Movies.Contracts;

namespace Rodunu.Movies.Web.Security
{
    public class WebAuthentication
    {
        /// <summary> Sets the authicated cookie.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="rememberMe">if set to <c>true</c>, to user will be remembered.</param>
        /// <param name="cookiePath">The cookie path.</param>
        /// <param name="response">The Web Response</param>
        public virtual void SetAuthCookie(UserInfo user, bool rememberMe, string cookiePath, IResponse response)
        {
            var cookie = new HttpCookie("RodunuCookie", user.Id.ToString());
            cookie.Expires = rememberMe ? DateTime.Now.AddDays(10) : DateTime.Now.AddHours(1);
            response.CreateCookie(cookie);
        }

        /// <summary> Signs the out the user.
        /// </summary>
        public virtual void SignOut(IResponse response, IRequest request)
        {
            try
            {
                response.RemoveCookie("RodunuCookie");

                request.ReadCookie("RodunuCookie");
                var cookie = new HttpCookie("RodunuCookie", "0");
                response.CreateCookie(cookie);
                
            }
            catch (Exception ex)
            {
                //TODO: Log exception
            }
            
            FormsAuthentication.SignOut();
            HttpContext.Current.Session.Abandon();
        }
    }
}
